package io.gitee.itxinmeng.encrypt.spring.boot.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author mx
 */
public class ServletUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServletUtil.class);
    /**
     * Get the String value by key in parameters
     * @param headers ServerHttpRequest.getHeader
     * @param name key in parameters
     * @return string
     */
    public static String getHeader(HttpHeaders headers, String name){
        List<String> list = headers.get(name);
        if(CollectionUtil.isNotEmpty(list)){
            return CollectionUtil.join(list,",");
        }else{
            return "";
        }
    }

    public static String getBodyString(HttpInputMessage inputMessage)
    {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try (InputStream inputStream = inputMessage.getBody())
        {
            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line = "";
            while ((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
        }
        catch (IOException e)
        {
            LOGGER.warn("getBodyString error！");
        }
        finally
        {
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (IOException e)
                {
                    LOGGER.error(e.getMessage());
                }
            }
        }
        return StrUtil.replace(sb.toString(),"\"","");
    }

    /**
     *
     * @param headers
     * @param appSecret
     * @return check sign success or fail
     */
    public static Boolean checkSign(HttpHeaders headers, String appSecret){
        String appKey = getHeader(headers,"appKey");
        String timestamp = getHeader(headers,"timestamp");
        String version = getHeader(headers,"version");
        String sign = getHeader(headers,"sign");
        if(StrUtil.isBlank(appKey)
                || StrUtil.isBlank(sign)
                || StrUtil.isBlank(timestamp)
                || StrUtil.isBlank(version)){
            return Boolean.FALSE;
        }
        String signStr = StrUtil.format("{}{}{}{}",appKey,timestamp,version,appSecret);
        String signNew = SecureUtil.md5(signStr);
        if(signNew.equals(sign)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
